/* eslint-disable no-undef */
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Router from 'vue-router'
import store from './store'
import axiox from './httpConfig/http'
import base from './mixins/base'
import rongMixin from './mixins/IM'
import wxMixin from '@/mixins/WX'
import remAndPhoneConfig from './config/remConfig'
import Vant from 'vant'
import 'vant/lib/index.css'
import notice from '@/components/notice'
import ContentBox from '@/components/ContentBox'
import './theme/public.scss'

remAndPhoneConfig()

Vue.use(Vant)
Vue.use(Router)

Vue.mixin(base)
Vue.mixin(rongMixin)
Vue.mixin(wxMixin)
Vue.component('ContentBox', ContentBox)
Vue.component('notice', notice)

// 重写路由push方法
const routerPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}

Vue.config.productionTip = false
Vue.prototype.$axios = axiox

const isIos = base.methods.$isIOS()

if (isIos) {
  window.setupWebViewJavascriptBridge = function (callback) {
    if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge) }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback) }
    window.WVJBCallbacks = [callback]
    const WVJBIframe = document.createElement('iframe')
    WVJBIframe.style.display = 'none'
    WVJBIframe.src = 'https://__bridge_loaded__'
    document.documentElement.appendChild(WVJBIframe)
    setTimeout(function () { document.documentElement.removeChild(WVJBIframe) }, 0)
  }

  // OBJC eCHO
  window.iosCallHandler = (funName, params = '') => {
    return new Promise(resolve => {
      window.setupWebViewJavascriptBridge(function (bridge) {
        bridge.callHandler(funName, params, function (responseData) {
          resolve(responseData)
        })
      })
    })
  }

  // JS Echo
  window.iosRegisterHandler = (funName) => {
    return new Promise(resolve => {
      window.setupWebViewJavascriptBridge(function (bridge) {
        bridge.registerHandler(funName, function (data, responseCallback) {
          responseCallback(data)
          resolve(data)
        })
      })
    })
  }
}

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

router.beforeEach((to, from, next) => {
  store.commit('SET_PATH', to.fullPath)
  localStorage.setItem('path', to.fullPath)
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (store.state.token && store.state.token !== '' && localStorage.getItem('token') && localStorage.getItem('token') !== '') { // 通过vuex state获取当前的token是否存在
      next()
    } else {
      if (store.getters.pl === 'H5') {
        next({
          path: '/login',
          query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
        })
      } else if (store.getters.pl === 'ANDROID') {
        AndroidJsBridge.login()
      } else if (store.getters.pl === 'IOS') {
        window.iosCallHandler('pushLoginVC')
      }
    }
  } else {
    next()
  }
})
